package com.sadhoc.sockets;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import com.sadhoc.router.PacketReceiver;
import com.sadhoc.router.pdu.HDPacket;

public class UDPReceiver implements Runnable {
	
	private PacketReceiver receiver	= null;
	private DatagramSocket socket 	= null;
	boolean running = true;
	
	/*
	 * Constructor
	 */
	public UDPReceiver(int port, PacketReceiver receiver) throws SocketException {
		
		this.receiver = receiver;
		socket = new DatagramSocket(port);
		
	}

	/*
	 * Listens for UDP datagrams and adds it to the packet receiver queue
	 */
	public void run() {
		
		try {
			byte[] buffer = new byte[6000];
			while (running) {
				
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				socket.receive(packet);
				HDPacket hdp = new HDPacket(packet.getData());
				receiver.addQueue(hdp);
			
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
			
	}
	
	/*
	 * Stops the thread
	 */
	public void stop() {
		
		running = false;
		socket.close();		
		socket = null;
		
		
	}

}
